﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cosmetic.DataEntity;

namespace Cosmetic.Logic
{
	/// <summary>
	/// Category manager class
	/// </summary>
	public class CategoryManager : LogicBase
    {
		/// <summary>
		/// top level category
		/// </summary>
		public enum ETopCategory
		{
			/// <summary>
			/// Product category. ie: 美白, 防晒...
			/// </summary>
			Product,

            /// <summary>
            /// Product category. ie: 美白, 防晒...
            /// </summary>
            Category_L,

			/// <summary>
			/// ie:欧美品牌，日本品牌，韩国品牌，其他...
			/// </summary>
			BrandArea,
			/// <summary>
			/// forum board categroy. ie: 脸部保养, 彩妆...
			/// </summary>
			Forum,
			/// <summary>
			/// topic state. ie: Top, Close ...
			/// </summary>
			TopicState,
			/// <summary>
			/// content category. ie: 最新情报, 美丽宝典...
			/// </summary>
			Content,
			/// <summary>
			/// tag attached to which category. ie: Comment, Content
			/// </summary>
			Tag,
			/// <summary>
			/// user role. ie: Admin, Blog, ForumAdmin
			/// </summary>
			Role,
			/// <summary>
			/// user skin kind. ie: 干性, 油性...
			/// </summary>
			UserSkin,
			/// <summary>
			/// user hair kind. ie: 中性, 受损...
			/// </summary>
			UserHair,
			/// <summary>
			/// job kind. ie: 工程师, 营业员...
			/// </summary>
			Job,
			/// <summary>
			/// cost range. ie: 0--100, 100-200...
			/// </summary>
			Cost,
			/// <summary>
			/// education. ie: 小学, 中学, 大学...
			/// </summary>
			Education,
			/// <summary>
			/// 购买渠道. ie: 专柜, 超市 ....
			/// </summary>
			PurchaseChannels,
			/// <summary>
			/// 博客的类别
			/// </summary>
			Blog,
            /// <summary>
			/// 博客文章的类别
			/// </summary>
			Topic
		}

        /// <summary>
        /// 判断是否有类别，如果有返回true，否则返回false.
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool IsExistTheName(string name)
        {
            var ex = (from category in m_CosmeticDC.Categories
                      where category.Name == name
                      select category).ToList();
            if (ex != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


		/// <summary>
		/// Insert a new Category into database
		/// </summary>
		/// <param name="aCategory">new Category</param>
		public void Insert(Category aCategory)
		{
			if (aCategory.Index == 0)
			{
				aCategory.Index		= m_CosmeticDC.Categories.Max(theCategory=>theCategory.Index)+1;
			}
			m_CosmeticDC.Categories.InsertOnSubmit(aCategory);
			m_CosmeticDC.SubmitChanges();
		}

		/// <summary>
		/// Delete Category
		/// </summary>
		/// <param name="aCategory">The Category want delete</param>
		public void Delete(Category aCategory)
		{
			m_CosmeticDC.Categories.DeleteOnSubmit(aCategory);
			m_CosmeticDC.SubmitChanges();
		}





		/// <summary>
		/// check top level category whether or not exist, if not exist then creat it.
		/// </summary>
		public void CheckTopCategory()
		{
			Type theTopCategoryType		= typeof(ETopCategory);
			foreach (string theTopCategoryName in Enum.GetNames(theTopCategoryType))
			{
				ETopCategory theTopCategoy	= (ETopCategory)Enum.Parse(typeof(ETopCategory), theTopCategoryName);
				if (GetTopCategryByName(theTopCategoy) == null)
				{
					Category theTopCategory			= new Category();
					theTopCategory.Name				= theTopCategoryName;
					theTopCategory.CategoryId		= Guid.NewGuid();
					theTopCategory.SupCategoryId	= theTopCategory.CategoryId;
					theTopCategory.CreateTime		= DateTime.Now;
					Insert(theTopCategory);
				}
			}
		}

		/// <summary>
		/// check the supcategory whether or not contains subcategory.
		/// </summary>
		/// <param name="aSupCategory">supcategory</param>
		/// <param name="aSubCategoryName">subcategory name</param>
		/// <returns>if contians return true else return false</returns>
		public bool CheckContains(Category aSupCategory, string aSubCategoryName)
		{
			return this.CheckContains(aSupCategory.CategoryId, aSubCategoryName);
		}
		/// <summary>
		/// check the supcategory whether or not contains subcategory.
		/// </summary>
		/// <param name="aSupCategoryId">supcategory id</param>
		/// <param name="aSubCategoryName">subcategory name</param>
		/// <returns>if contians return true else return false</returns>
		public bool CheckContains(Guid aSupCategoryId, string aSubCategoryName)
		{
			List<Category> theCategoryList	= (from theCategory in m_CosmeticDC.Categories
											  where theCategory.SupCategoryId == aSupCategoryId && theCategory.Name == aSubCategoryName
											  select theCategory).ToList();
			return theCategoryList.Count > 0;
		}

		/// <summary>
		/// Get Category by Category Id
		/// </summary>
		/// <param name="aCategoryId">Category Id</param>
		/// <returns>Category</returns>
		public Category GetCategoryById(Guid aCategoryId)
		{
            try
            {
                return m_CosmeticDC.Categories.Single(theCategory => theCategory.CategoryId == aCategoryId);
            }
            catch
            {
                return null;
            }
        }

        public Category GetCategoryById1ss(int aCategoryId)
        {
            try
            {
                return m_CosmeticDC.Categories.Single(theCategory => theCategory.Index == aCategoryId);
            }
            catch
            {
                return null;
            }
        }


        /// <summary>
        /// Get Category by Category Id
        /// </summary>
        /// <param name="aCategoryId">Category Id</param>
        /// <returns>Category</returns>
        public string  GetNameByCategoryId(Guid aCategoryId)
        {
            var name = (from cate in m_CosmeticDC.Categories
                        where cate.CategoryId == aCategoryId
                        select cate.Name
                          ).Single();
            return name;
        }


        public List<Category> GetUpCategoryBySupCategoryID(Guid aCategoryID)
        {
            var aa = (from cate in m_CosmeticDC.Categories
                      where cate.SupCategoryId == aCategoryID
                      select cate).ToList();
            return aa;
        }

        /// <summary>
        /// 得到这一级的Category类。
        /// </summary>
        /// <param name="aCategoryID"></param>
        /// <returns></returns>
        public Category GetCategoryByCategoryID(Guid aCategoryID)
        {
            var aa = (from cate in m_CosmeticDC.Categories
                      where cate.CategoryId == aCategoryID
                      select cate).Single();
            return aa;
        }

        public List< Category> GetUpCategoryById(Guid aCategoryID)
        {
            var aa = (from cate in m_CosmeticDC.Categories
                     where cate.SupCategoryId == (from category in m_CosmeticDC.Categories
                                                  where category.CategoryId == aCategoryID
                                                  select category.SupCategoryId).Single()
                      orderby cate.CreateTime descending
                     select cate).ToList();
            return aa;
        }

        /// <summary>
        /// 用来得到上一级的CategoryId.
        /// </summary>
        /// <param name="aCategoryID"></param>
        /// <returns></returns>
        public Category GetFrontCategoryById(Guid aCategoryID)
        {
            var aa = (from cate in m_CosmeticDC.Categories
                      where cate.CategoryId == (from category in m_CosmeticDC.Categories
                                                   where category.CategoryId == aCategoryID
                                                   select category.SupCategoryId).Single()
                      select cate).Single();
            return aa;
        }

        public List<Category> GetCategoryById_L(Guid aCategoryID)
        {
            var aa = (from cate in m_CosmeticDC.Categories
                      where cate.SupCategoryId == aCategoryID
                      orderby cate.CreateTime descending
                          select cate).ToList();
            return aa;
        }

        public string GetCategoryByID(string str)
        {
            try
            {
                var strTem = (from cate in m_CosmeticDC.Categories
                              where cate.Name == str
                              select cate.CategoryId).Single().ToString();
                return strTem;
            }
            catch
            { return ""; }
        }

        public string GetCategoryIdByName(string CategoryName)
        {
            var result = from cate in m_CosmeticDC.Categories
                         where cate.Name == CategoryName
                         select cate;
            return result.First().CategoryId.ToString();
        }

        /// <summary>
        /// Get Category by Category Name
        /// </summary>
        /// <param name="aCategoryId">Category Name</param>
        /// <returns>Category</returns>
        public Category GetCategoryByName(string aCategoryName)
        {
            try
            {
                return m_CosmeticDC.Categories.First(theCategory => theCategory.Name == aCategoryName);
            }
            catch
            {
                return null;
            }
        }
		
		/// <summary>
		/// 显示全部的类别
		/// <param name="aSupCategory">supcategory</param>
		/// <returns>subcategories</returns>
		public List<Category> GetSubCateogoriesBySupCategory(Category aSupCategory)
		{
            try
            {
                return GetSubCateogoriesBySupCategory(aSupCategory.CategoryId);
            }
            catch
            {
                return null;
            }
		}
        /// <summary>
        /// 显示类别除了全国产地
        /// </summary>
        /// <param name="aSupCategory">supcategory</param>
        /// <returns>subcategories</returns>
        public List<Category> GetSubCateogoriesBySupCategorys(Category aSupCategory)
        {
            try
            {
                return GetSubCateogoriesBySupCategorys(aSupCategory.CategoryId);
            }
            catch
            {
                return null;
            }
        }


		/// <summary>
		/// get subcatgories by supcategory id
		/// </summary>
		/// <param name="aSupCategoryId">supcategory id</param>
		/// <returns>subcategories</returns>
		public List<Category> GetSubCateogoriesBySupCategory(Guid aSupCategoryId)
		{
           var result =  (from theCategory in m_CosmeticDC.Categories
             where theCategory.SupCategoryId == aSupCategoryId &&  theCategory.CategoryId != theCategory.SupCategoryId 
             orderby theCategory.CreateTime descending
             select theCategory).ToList();
           return result;
		}


        public List<Category> GetSubCateogoriesBySupCategorys(Guid aSupCategoryId)
        {
            var result = (from theCategory in m_CosmeticDC.Categories
                          where theCategory.SupCategoryId == aSupCategoryId && theCategory.CategoryId != theCategory.SupCategoryId && theCategory.count == 0
                          orderby theCategory.CreateTime descending
                          select theCategory).ToList();
            return result;
        }
		
		/// <summary>
		/// get top level category by category name, if not find the category create it
		/// </summary>
		/// <param name="aTopCategory">top level category</param>
		/// <returns>top level category</returns>
		public Category GetTopCategryByName(ETopCategory aTopCategory)
		{
			List<Category> theCategoryList	= (from theCategory in m_CosmeticDC.Categories
												where theCategory.Name == aTopCategory.ToString() && theCategory.CategoryId == theCategory.SupCategoryId
												select theCategory).ToList();
			if (theCategoryList.Count == 0)
			{
				Category theCategory		= new Category();
				theCategory.Name			= aTopCategory.ToString();
				theCategory.CategoryId		= Guid.NewGuid();
				theCategory.CreateTime		= DateTime.Now;
				theCategory.SupCategoryId	= theCategory.CategoryId;
				this.Insert(theCategory);
				return this.GetTopCategryByName(aTopCategory);
			}
			return theCategoryList[0];
		}

        /// <summary>
        /// get second level category by category name, if not find the category create it
        /// </summary>
        /// <param name="aCategoryName">second level name</param>
        /// <param name="aTopCategory">top level category</param>
        /// <returns>second level category</returns>
        public Category GetSecondCategoryByName(String aCategoryName, ETopCategory aTopCategory)
        {
            Category theTopCategory = GetTopCategryByName(aTopCategory);

            List<Category> theCategoryList = (from theCategory in m_CosmeticDC.Categories
                                              where theCategory.Name == aCategoryName && theTopCategory.CategoryId == theCategory.SupCategoryId
                                              select theCategory).ToList();
            if (theCategoryList.Count == 0)
            {
                Category theCategory = new Category();
                theCategory.Name = aCategoryName;
                theCategory.CategoryId = Guid.NewGuid();
                theCategory.CreateTime = DateTime.Now;
                theCategory.SupCategoryId = theTopCategory.CategoryId;
                this.Insert(theCategory);
                return this.GetSecondCategoryByName(aCategoryName, aTopCategory);
            }
            return theCategoryList[0];
        }

		/// <summary>
		/// get all top level category
		/// </summary>
		/// <returns>all top level category list</returns>
		public List<Category> GetAllTopCategory()
		{
			return (from theCategory in m_CosmeticDC.Categories
						where theCategory.CategoryId == theCategory.SupCategoryId
						orderby theCategory.CreateTime descending
						select theCategory).ToList();
		}

        public Dictionary<String, Guid> GetBlogCategory(Category aCategory)
        {
            Category theTopCategory = GetTopCategryByName(CategoryManager.ETopCategory.Topic);

            List<Category> theCategoryList = GetSubCateogoriesBySupCategory(theTopCategory.CategoryId);
            Dictionary<String, Guid> theCategories = new Dictionary<String, Guid>();
            if (theCategoryList.Count() > 0)
            {
                IOrderedQueryable<Blog> theBlogList = m_CosmeticDC.Blogs.Where(theBlog => theBlog.BlogCategory == aCategory).OrderBy(theBlog => theBlog.BlogCategoryId);

                foreach (Category theCategory in theCategoryList)
                {
                    String theKey = String.Format("{0} ({1}篇)",
                                        theCategory.Name,
                                        theBlogList.Count(theBlog => theBlog.CategoryId == theCategory.CategoryId));
                    theCategories.Add(theKey, theCategory.CategoryId);
                }
            }
            return theCategories;
        }
	}
}
